package cn.felord.common.controller;


import cn.felord.common.bean.Menu;
import cn.felord.common.bean.Rest;
import cn.felord.common.bean.RestBody;
import cn.felord.common.entity.SysResources;
import cn.felord.common.service.ISysResourcesService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.support.Property;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.LinkedHashSet;

/**
 * <p>
 * 资源表 前端控制器
 * </p>
 *
 * @author dax
 * @since 2018 -09-13
 */
@RestController
@RequestMapping("/res")
public class SysResourcesController {
    @Resource
    private ISysResourcesService iSysResourcesService;


    /**
     * Gets menu by user id.
     *
     * @param userId the user id
     * @return the menu by user id
     */
    @GetMapping("/user/{userId}")
    public Rest getMenuByUserId(@PathVariable String userId) {
        LinkedHashSet<Menu> menuLinkedHashSet = iSysResourcesService.findMenuByUserId(userId);
        return RestBody.okData(menuLinkedHashSet);
    }

    /**
     * Add resource rest.
     *
     * @param sysResources the sys resources
     * @return the rest
     */
    @PostMapping("/add")
    public Rest addResource(SysResources sysResources) {
        sysResources.setCreateTime(LocalDateTime.now());
        boolean save = iSysResourcesService.save(sysResources);
        return save ? RestBody.ok("添加成功") : RestBody.failure("添加失败");
    }

    /**
     * Check rest.
     *
     * @param resourceName the resource name
     * @return the rest
     */
    @GetMapping("/checkName")
    public Rest check(String resourceName) {
        Integer check = check(SysResources::getResourceName, resourceName);
        return check > 0 ? RestBody.failure("资源名称不能重复") : RestBody.ok();
    }


    /**
     * Menu list rest.
     *
     * @return the rest
     */
    @GetMapping("/list")
    public Rest menuList() {
        LinkedHashSet<Menu> menuLinkedHashSet = iSysResourcesService.findMenuByUserId("");
        return RestBody.okData(menuLinkedHashSet);
    }

    /**
     * Menu list rest.
     *
     * @param pid the pid
     * @return the rest
     */
    @GetMapping("/dir/pid/{pid}")
    public Rest mainDir(@PathVariable String pid) {
        return RestBody.okData(iSysResourcesService.findMenuByParentId(pid));
    }


    private Integer check(Property<SysResources, ?> property, Object val) {
        QueryWrapper<SysResources> sysResourcesQueryWrapper = new QueryWrapper<>();
        sysResourcesQueryWrapper.lambda().eq(property, val).eq(SysResources::getState, '1');
        return iSysResourcesService.count(sysResourcesQueryWrapper);
    }
}
